<!-- 聊天 ifdef-->
<template>
    <view class=" page--divider" style="min-height: auto; position: relative;">
       <headerline navstyle="left:18%;width:60%;" :reditem="unreadnum" :issearch="false" :showsearch="showsearch"
             @clicksearch='clicksearch' :shownav="false" :title="navtitle" :menuitem="menuitem"
            :navselect="navselect" :statusbarheight='statusBarHeight' :islogo="false" @tapnav="tapnav"
            @tapmenu="tapmenu" rightmenu="true"  @closeSearch="closeSearch"></headerline>
        
        <view class="widget" v-if="navselect==0  && !showsearch">
            <scroll-view v-if="chats.length>0" refresher-enabled='true' refresher-threshold='60'
                :refresher-triggered="isfresh" :refresher-default-style='refreshstyle'
                @refresherpulling='refresherpulling' @refresherrefresh='refresherrefresh'>
                <view class="fresh" v-if="isfresh==true">
                    {{fresh_tip}}
                </view>
                <view :class="{'item':true,'istop':item.istop}" v-for="(item, index) in chats" :key="item.key"
                    @tap="handleClick(item)" @longtap="msgAction(item)">
        
                    <image :src="image_cache(item.avatar)" class="leftImg" />
                    <view class="rightContent" >
                        <view class="topCont">
                            <view class="userName">{{item.nickname||'匿名'}}</view>
                            <view class="time">{{ timestamp(item.timestamp) || '--:--' }}</view>
                        </view>
                        <view class="bottomCont">
                            <view class="content" v-if="item.message.type!='tips'">
                                <block v-if="item.self || item.sender.nickname!=undefined">
                                    {{item.self? '[我]': ''}}
                                </block>
                                <text style='color: #999;font-size: 22upx' v-if="item.message.type == 'emoji'">[表情]</text>
                                <text style='color: #999;font-size: 22upx' v-if="item.message.type == 'voiceCancel'">通话{{item.message.content}}</text>
                                <text style='color: #999;font-size: 22upx' v-if="item.message.type == 'voiceTime'">{{item.message.content.payload}}</text>
                               <text style='color: #999;font-size: 22upx'
                                    v-if="item.message.type=='voice'">[语音]</text>
                                <text style='color: #999;font-size: 22upx'
                                    v-else-if="item.message.type=='redpacket'">[红包]</text>
                                <text style='color: #999;font-size: 22upx'
                                    v-else-if="item.message.type=='image'">[图片]</text>
                                <text style='color: #999;font-size: 22upx'
                                    v-else-if="item.message.type=='vedio'">[视频]</text>
                                <text style='color: #999;font-size: 22upx'
                                    v-else-if="item.message.type=='emotion'">[表情]</text>
                                <text style='color: #999;font-size: 22upx'
                                    v-else-if="item.message.type=='audio'">{{item.message.content.text}}</text>
                                <text style='color: #999;font-size: 22upx' v-else-if="item.message.type=='tips'">
                                    <block style="font-size: 22upx" v-if="item.message.content.type=='time'">
                                        {{item.message.content.text}}
        
                                    </block>
                                    <block v-else style="font-size: 22upx">
                                        {{item.message.content}}
                                    </block>
        
        
                                </text>
        
        
                                <text style='color: #999;font-size: 22upx' v-else-if="item.message.type=='text'">
        
                                    <text v-if="item.message.content.type!='emotion' ">
        
                                        <block
                                            v-if="item.message.content.type=='remind' && toText(item.message.content.content).indexOf('@我')>-1 ">
                                            <text style="color:#1d830a">
                                                {{item.message.content.type=="remind"?toText(item.message.content.content):toText(item.message.content) }}</text>
                                        </block>
                                        <block v-else>
                                            {{item.message.content.type=="remind"?toText(item.message.content.content):toText(item.message.content) }}
                                        </block>
        
                                    </text>
                                    <text v-if="item.message.content.type=='emotion' ">
                                        {{item.message.content.content}}
                                    </text>
        
                                </text>
                                <text style='color: #999999;font-size: 22upx' v-else-if="item.message.msg_type=='show'">
                                    {{item.message.content.text}}
                                </text>
                            </view>
                            <view class="content" v-else>
                                <text style='color: #999999;font-size: 22upx'>
                                    <block v-if="item.message.content.type=='time'">
                                        {{item.message.content.text}}
        
                                    </block>
                                    <block v-else>
                                        {{item.message.content}}
                                    </block>
        
                                </text>
                            </view>
                            <view class="badge" v-if="item.unread && item.unread>99"
                                style="width: auto;padding: 0 5px;">99+</view>
                            <view class="badge" v-if="item.unread && item.unread<=99">{{item.unread}}</view>
                        </view>
                    </view>
                </view>
            </scroll-view>
            <view v-else class="nodata">
                您还没有任何消息
            </view>
        </view>
       <!-- <view class="conversations" style="background: red;" scroll-y="true">
  
        	<view v-if="conversations.length > 0">
        		<view class="scroll-item" :style="conversation.top?'background: #f8f8f8;':'background: #fff;'" v-for="(conversation, key) in conversations" :key="key">
        			<view class="item-head">
                        
        				<image style="border-radius: 10rpx;" :src="conversation.lastMessage.type!='addUser'?conversation.data.avatar:image_cache(conversation.lastMessage.payload.avatar)" class="head-icon"></image>
        				<view class="item-head_unread" v-if="conversation.unread">{{conversation.unread}}</view>
        			</view>
        			<view class="scroll-item_info" @click="navigateToChat(conversation)">
        				<view class="item-info-top">
        					<text class="item-info-top_name">{{conversation.lastMessage.type!='addUser'?conversation.data.name:conversation.lastMessage.payload.name}}</text>
        					<view class="item-info-top_time">{{formatDate(conversation.lastMessage.timestamp)}}</view>
        				</view>
        				<view class="item-info-bottom">
        					<view class="item-info-bottom-item">
        						<view class="item-info-top_content" v-if="!conversation.lastMessage.recalled">
                                    <text class="unread-text">{{conversation.lastMessage.read === false && conversation.lastMessage.senderId === currentUser.id?'[未读]':''}}</text>
        							<text v-if="conversation.type === 'private'">
                                    {{conversation.lastMessage.senderId === currentUser.id? '我': conversation.lastMessage.type!='addUser'?conversation.data.name:conversation.lastMessage.payload.name}}:
                                    </text>
        							<text v-else>{{conversation.lastMessage.senderId === currentUser.id? '我': conversation.lastMessage.senderData.name}}:</text>
        							<text v-if="conversation.lastMessage.type === 'text'">{{conversation.lastMessage.payload.text}}</text>
        							<text v-else-if="conversation.lastMessage.type === 'video'">[视频消息]</text>
        							<text v-else-if="conversation.lastMessage.type === 'audio'">[语音消息]</text>
        							<text v-else-if="conversation.lastMessage.type === 'image'">[图片消息]</text>
        							<text v-else-if="conversation.lastMessage.type === 'file'">[文件消息]</text>
                                    <text v-else-if="conversation.lastMessage.type === 'voiceTime'">[语音通话]</text>
                                    <text v-else-if=" conversation.lastMessage.type === 'emoji'">[表情]</text>
                                    <text v-else-if="conversation.lastMessage.type === 'voiceCancel'">[语音通话]</text>
        							<text v-else-if="conversation.lastMessage.type === 'redpacket'">[恭喜发财]</text>
                                    <text v-else-if="conversation.lastMessage.type === 'addUser'">{{conversation.lastMessage.payload.make}}</text>
        							<text v-else>[[未识别内容]]</text>
        						</view>
        						<view class="item-info-top_content" v-else>
        							<text v-if="conversation.type === 'private'">{{conversation.lastMessage.senderId === currentUser.id? '你': `"${conversation.data.name}"`}}撤回了一条消息</text>
        							<text v-if="conversation.type === 'group'">{{conversation.lastMessage.senderId === currentUser.id? '你': `"${conversation.lastMessage.senderData.name}"`}}撤回了一条消息</text>
        						</view>
        						<view class="item-info-bottom_action" @click.stop="showAction(conversation)"></view>
        					</view>
        				</view>
        			</view>
        		</view>
        	</view>
        	<view class="no-conversation" v-else>
        		当前没有会话
        	</view> 
        	<view class="action-container" v-if="actionPopup.visible">
        		<view class="layer" @click="actionPopup.visible = false"></view>
        		<view class="action-box">
        			<view class="action-item" @click="topConversation">{{actionPopup.conversation.top ? '取消置顶' : '置顶聊天'}}</view>
        			<view class="action-item" @click="deleteConversation">删除聊天</view>
        		</view>
        	</view>
        </view> -->
        <view @click="gua" v-show="showCall" style="z-index: 100; position: absolute; top: 200rpx;right: 15px;padding: 5rpx; box-shadow: 0 3rpx 3rpx #666; background: #fff;width: 60rpx;height: 60rpx;border-radius: 50px;">
            <image src="../../static/tong.png" style="width: 100%;height: 100%;"></image>
        </view>
    </view>
</template>

<script>
    import scode from "@/library/scode.js"
    import api from "@/library/index.js"
    import chat from "@/library/chat.js"
    import http from "@/library/http.js"
    import message from "@/library/message.js"
    import action from "@/library/action.js"
    import headerline from '@/components/header.vue'
    import utils from '@/library/common.js'
    var windowHeight = uni.getSystemInfoSync().windowHeight;
    var statusBarHeight = uni.getSystemInfoSync().statusBarHeight;
    var contenttop = statusBarHeight + 45;
    var conentheight = windowHeight - contenttop;
    var lottHeight = conentheight - 30;
    var lottTop = contenttop + 30;
    const GoEasy = uni.$GoEasy;
    const GRTC = uni.$GRTC;
    import silenceUpdate from '@/uni_modules/rt-uni-update/js_sdk/silence-update.js'
    export default {
        components: {
            headerline,

        },
        data() {
            return {
                statusBarHeight: statusBarHeight + 'px',
                contenttop: contenttop + 'px',
                contentheight: conentheight + 'px',
                lottHeight: lottHeight + 'px',
                lottTop: lottTop + 'px',
                shownav: false,
                // navtitle:'消息',
                navselect: 0,
                menuitem: [],
                newfriendNotify: false,
                showMenu: false,
                newfriendnum: 0,
                clickkey: false,
                reading_id: -1,
                actions: [],
                user: uni.getStorageSync('userInfo'),
                showsearch: false,
                friends: uni.getStorageSync(uni.getStorageSync('access_token') + '_frienddata'),
                pinyin: [],
                char_select: false,
                kefunum: 0,
                unreadnum: [0, 0, 0],
                refreshstyle: 'none',
                isfresh: false,
                fresh_tip: '下拉刷新',
                threshold:60,//设置下拉阀值
                unreadTotal : 0,
                conversations : uni.getStorageSync('CallData'),
                // conversations : uni.getStorageSync('CallData'),
                currentUser:uni.getStorageSync('userInfo'),
                actionPopup : {
                	conversation : null,
                	visible : false
                },
                phonNumber:uni.getStorageSync('phone'),
                showCall:false,
                yanIndex:0
            }
        },
        computed: {
            chats() {
                var res = this.$store.getters['chat/msglist'];
                console.log('dadad------------------------------',res)
                return res;
            },
            navtitle() {
                var num = 0;
                var msg_list = this.$store.getters['chat/msglist'];
                msg_list.map(item => {
                    num += parseInt(item.unread)
                })
                let user = uni.getStorageSync('userInfo')
                if(num > 0){
                    // 设置桌面数字徽标
                    uni.setTabBarBadge({
                    	index: 0,
                    	text: num.toString()
                    });
                } else {
                    uni.removeTabBarBadge({
                    	index: 0
                    });
                }
                return `消息(${user.isonline == 1?'在线':'离线'})`
            }

        },
        watch: {
            chats(val) {
                var num = 0;
                for (var i = 0; i < val.length; i++) {
                    num += val[i].unread;
                }
                this.unreadnum.splice(0, 3);
                this.unreadnum.push(num);
                this.unreadnum.push(0);
                this.unreadnum.push(0);
                this.$forceUpdate();
            },
            unreadTotal(val,old){
                if(val > 0){
                    utils.playAudios('/static/voice/apply.mp3');
                    uni.setTabBarBadge({
                    	index: 0,
                    	text: this.unreadTotal.toString()
                    });
                }
            }
        },

        methods: {
          check_update() {
              /** 检测升级 */
              // #ifdef APP-PLUS
              let _this = this;
              plus.runtime.getProperty(plus.runtime.appid, function(info) {
                  api.update({
                      version: info.version,
                      osname: plus.os.name
                  }).then(res => {
                      if (res.data.status == 1) {
                          let data = {
                              describe: '',
                              edition_url: res.data.downurl,
                              edition_force: 0, //强制更新
                              package_type: 1, //是否整包更新
                              edition_number: '1.1.1',
                              edition_name: '1.1.6',
                              edit_silence: 0
                          }
                          // silenceUpdate(data)
                          uni.navigateTo({
                              url: '/uni_modules/rt-uni-update/components/rt-uni-update/rt-uni-update?obj='+JSON.stringify(data)
                          }); 
                          
                      }
                  })
          
              });
              // #endif
          },
            gua(){
                console.log('带你打')
                uni.navigateTo({
                    url:'/pages/rtc/private/call'
                })
            },
            getuserinfo() {
                var postdata = {
                    id: uni.getStorageSync('access_token')
                };
                http.setWait(false).post('user.php?act=userinfo', postdata).then(res => {
                    this.user = res.data;
                    uni.setStorageSync('userInfo', this.user)
                })
            
            },
 
			search(e) {
				console.log('search',e)
			},
			closeSearch() {
				
			},
            refresherpulling() {

                this.refreshstyle = 'none';
                this.isfresh = true;
                this.fresh_tip = '下拉刷新...';
                // this.listenConversationUpdate(); //监听会话列表变化
                // this.loadConversations(); //
            },
            refresherrefresh() {
                this.refreshstyle = 'black';
                this.fresh_tip = '正在刷新...';
                this.lastchat();
                // this.listenConversationUpdate(); //监听会话列表变化

            },
            href(path, opts) {

                if (!opts || opts == undefined || opts == null) opts = {};
                this.$jump(path, opts);

            },
            open_detail(item) {

                this.$jump('friend.detail', {
                    id: item.id
                });
            },
            toText(str) {
                str = str.toString()
                str = str.replace(/&nbsp;/g, " ");
                str = str.replace(/<br>/g, " ");
                str = str.replace(/<[^<>]+>/g, '')
                return str;
            },
            timestamp(time) {
                // return  action.timestampFormat(new Date(time.replace(/(-|年|月)/g, '/').replace('日', '')).getTime()/1000)
                return action.timestampFormat(time)
            },

            tapnav(num) {
                this.navselect = num;
                if (num == 1) this.friendlist();
                else this.lastchat();
            },
            clicksearch(e) {
                this.showsearch = e;
            },
            go_search(e) {
                http.setWait(true).get('user.php?act=searchUser', {
                    keywords: e
                }).then(res => {
                    if (res.data.length > 0) {
                        var id = res.data[0].id;
                        uni.navigateTo({
                            url: '../friend/detail?id=' + id + '&from=' + res.data[0].from
                        })

                    } else {
                        uni.showToast({
                            icon: 'none',
                            title: '没有搜索到相关用户',
                            duration: 1500
                        })
                    }
                })

            },
            tapmenu(num) {

                if (this.$action.loginTips('未登录用户，无法完成此操作', '/pages/game/index') == false) return false;
                if (this.$action.check_userlock() == false) return false;

                if (num == 0) {

                    if (this.user.nickname == '' || this.user.nickname == this.user.name) {
                        this.$action.profileTips('未设置昵称，不能创建群', '/pages/group/create');
                        return false;
                    } else
                        this.$jump('group.create');
                }
                //  else if (num == 1) {
                //     this.$jump('group.list', {
                //         method: 0
                //     });
                // } else if (num == 2) {
                //     this.$jump('group.list', {
                //         method: 1
                //     });
                // }
                else if (num == 1) {
					uni.navigateTo({
						url: '../friend/searchFriend'
					})
				}
				 // else if (num == 4) {
     //                this.$jump('mine.note');
     //            } 
				else if (num == 2) {
                    
                    return uni.scanCode({
                        success(res) {
                            console.log('撒大大大',res)
                            scode.getScode(res)
                        },
                        fail(e) {
                            // console.log(JSON.stringify(e));
                            console.log('扫码失败')
                        }
                    });
                }
            },
            group_read(group_id) {

                http.setWait(false).post('group.php?act=setReadTime', {
                    group_id: group_id,
                    userid: this.user.id
                }).then(res => {

                    this.lastchat();
                })

            },
            user_read(userid) {
                http.setWait(false).post('group.php?act=setReadTime', {
                    group_id: 0,
                    userid: this.userid,
                    sendid: this.user.id
                }).then(res => {
                    this.lastchat();
                })

            },
            handleClick(info) {
                if (info.unread > 0) this.$store.commit('chat/clearunread', info.cache_key);
                if (this.clickkey == info.cache_key) return false;
                this.clickkey = info.cache_key;
                if (info.cache_key == "U1") {
                    return this.$jump('friend.request?type=' + info.sender.id);
                } else {
                    if (info.cache_key.indexOf('U') > -1) {
                        let friend = {
                            id: info.id,
                            nickname: info.nickname
                        }
                        this.user_read(info.id);
                     //    uni.navigateTo({
                     //        url:'/pages/friend/privateChat/privateChat?id='+info.id+'&nickname='+info.nickname+'&avatar='+info.avatar
                     //    })
                     
                        // return
                        return this.$jump('friend.chat', friend);
                    } else {
                        if (info.message.content.type == 'remind' && this.toText(info.message.content.content).indexOf(
                                '@我') > -1)
                            var atme = 1;
                        else var atme = 0;
                        this.group_read(info.id);
                        // uni.navigateTo({
                        //     url:'/pages/friend/groupChat/groupChat?id='+info.id+'&nickname='+info.nickname
                        // })
                        this.$jump('group.chat', {
                            id: info.id,
                            nickname: info.nickname,
                            atme: atme,
                            msg_id: info.msg_id
                        });
                    }

                }

            },

            msgtopChanage(istop, cache_key) {
                istop = !istop

                var msgtop = uni.getStorageSync('msgtop') ? uni.getStorageSync('msgtop') : [];
                if (istop) {
                    msgtop.push(cache_key)
                } else {
                    for (var i = 0; i < msgtop.length; i++) {
                        if (msgtop[i] == cache_key) {
                            msgtop.splice(i, 1)
                        }
                    }
                }

                uni.setStorageSync('msgtop', msgtop);
                this.$store.commit('chat/set_istop');
                var data = {
                    cache_key: cache_key,
                    userid: this.user.id,
                    istop: istop
                };

                http.setWait(false).get('group.php?act=set_msgtop', data).then(res => {

                })

            },
            msgAction(msg) {


                var user_id = uni.getStorageSync('access_token');
                // console.log(msg);
                let that = this;
                var itemList = [];
                if (msg.istop < 1) itemList.push('置顶');
                else itemList.push('取消置顶');
                if (msg.unread > 0) itemList.push('标记已读');
                else itemList.push('标记未读');
                itemList.push('删除会话')
                uni.showActionSheet({
                    itemList: itemList,
                    success: function(res) {
                        switch (res.tapIndex) {
                            case 2:

                                that.delete_msg(msg.cache_key)
                                break;
                            case 0:
                                that.msgtopChanage(msg.istop, msg.cache_key)
                                // console.log(msg.cache_key)
                                break;
                            case 1:
                                that.$store.commit('chat/set_read', msg);
                                break;
                            default:
                                break;
                        }
                    },
                    fail: function(res) {
                        //console.log(res.errMsg);
                    }
                });



            },
            lastchat() {
                var userid = parseInt(uni.getStorageSync('access_token'));
                var postdata = {
                    userid: userid,
                    reading_id: this.reading_id
                };
                var msg_list_key = userid + '_chat_msglist';
                var temp1 = [];
                var temp2 = [];

                http.setWait(false).get('group.php?act=lastchat', postdata).then(res => {
                    var data = res.data;
                    var msglist = [];
                    let num = 0;
                    for (var i = 0; i < data.length; i++) {
                        num += Number(data[i].unread);
                        var item = data[i];
                        //  console.log(item)
                        //           console.log(item.cache_key,item.unread,this.timestamp(item.readtime))
                        var result = {};
                        result['key'] = userid + '_chat_' + item['cache_key'];
                        var msg = {};
                        msg['id'] = item.group.id;
                        msg['cache_key'] = item['cache_key'];
                        msg['group_id'] = item.group.id;
                        msg['nickname'] = item.group['nickname'];
                        // msg['kefu']=item.group.kefu
                        msg['avatar'] = item.group['avatar'];
                        msg['isloading'] = 1;
                        msg['istop'] = item.istop;
                        msg['msg_id'] = item.id;
                        msg['timestamp'] = item.addtime;
                        if (parseInt(item.userid) == userid) msg['self'] = 1;
                        else msg['self'] = 0;
                        msg['none'] = false;
                        msg['sender_id'] = item.userid;

                        msg['message'] = {
                            'type': item.type,
                            'content': item.content?item.content:' '
                        };
                        msg['unread'] = parseInt(item.unread);
                        msg['readtime'] = item.readtime;
                        if (item.groupid == 1) {
                            msg['sender'] = {
                                'nickname': item.sender_name,
                                id: item.reqtype
                            }
                        } else msg['sender'] = {
                            'nickname': item.sender_name
                        };
                        result['msg'] = msg;

                        if (msg.istop) temp1.push(result)
                        else temp2.push(result)
                    }

                    temp1.sort((a, b) => b.timestamp - a.timestamp);
                    temp2.sort((a, b) => b.timestamp - a.timestamp);
                    msglist = temp1.concat(temp2);

                    this.update_msglist(msglist);
                    console.log('dadasda------------',msglist)
                    var that = this;
                    this.fresh_tip = '刷新成功'
                    this.refreshstyle = 'none';
                    uni.hideLoading()
                    setTimeout(function() {
                        that.isfresh = false;
                    }, 500)

                })
            },
            //设置角标
            setBadge(num) {
                console.log('设置数字徽标',num)
                // #ifdef APP-PLUS
                    plus.runtime.setBadgeNumber(num)
                // #endif
                
            },
            //清除角标
            clearBadge() {
                // #ifdef APP-PLUS
                    plus.runtime.setBadgeNumber(-1)
                // #endif
            },

            setrightmenu() {
                var action = [

                    {
                        title: '新建群组',
                        icon: 'plus'
                    },
					{
					    title: '添加好友',
					    icon: 'plusempty'
					},
                    {
                        title: '扫一扫',
                        icon: 'scan'
                    },
                ]
                this.menuitem = action;
            },
            fresh_msg() {
                var msglist = uni.getStorageSync(uni.getStorageSync('access_token') + '_chat_msglist');
                this.update_msglist(msglist);
                this.$action.setStatusTips();
            },
           
            
            initGoEasyListeners() {
               GRTC.on(GRTC.EVENT.RING, this.onRing); //监听来电事件
            },
            onRing() {
              const currentCall = GRTC.currentCall();
              this.yanIndex ++
              if(currentCall){
                this.showCall = true
                if(currentCall.groupId) return 
                utils.playAudios('/static/voice/bd.mp3');
                uni.navigateTo({
                  url: `/pages/rtc/private/ring`,
                })
              } else {
                  this.showCall =  false
              }
            },
            // 加载最新的会话列表
            loadConversations() {
            	this.goEasy.im.latestConversations({
            		onSuccess: (result) => {
            			let content = result.content;
                        console.log('加载最新的会话列表',content)
            			this.renderConversations(content);
            			uni.hideLoading();
                        uni.stopPullDownRefresh();
            		},
            		onFailed: (error) => {
            			uni.hideLoading();
            			console.log('获取最新会话列表失败, error:',error);
                        uni.stopPullDownRefresh();
            		}
            	});
            },
            listenConversationUpdate() {
            	// 监听会话列表变化
            	this.goEasy.im.on(this.GoEasy.IM_EVENT.CONVERSATIONS_UPDATED, (content) => {
            		this.renderConversations(content);
            	});
            },
            subscribeGroup() {
            	let groupIds = []
                this.chats.map(item => {
                    if(item.cache_key.includes('G')){
                        groupIds.push(item.id)
                        return
                    }
                });
                console.log('订阅群消息成功',groupIds)
            	this.goEasy.im.subscribeGroup({
            		groupIds: groupIds,
            		onSuccess: function () {
            			console.log('订阅群消息成功');
            		},
            		onFailed: function (error) {
            			console.log('订阅群消息失败:', error);
            		}
            	});
            },
            topConversation() {  //会话置顶
            	uni.showLoading({
            		title:'加载中...',
            		mask: true
            	});
            	let actionPopup = this.actionPopup;
            	actionPopup.visible = false;
            
            	let conversation = actionPopup.conversation;
            	let failedDescription = conversation.top ? '取消置顶失败' : '置顶失败';
            	if(conversation.type === this.GoEasy.IM_SCENE.PRIVATE){
                    console.log('取消置顶失败',conversation.top)
            		this.goEasy.im.topPrivateConversation({
            			userId: conversation.userId,
            			top: !conversation.top,
            			onSuccess: function () {
            				uni.hideLoading();
            			},
            			onFailed: function (error) {
            				uni.hideLoading();
            				uni.showToast({
            					title: failedDescription,
            					icon: 'none'
            				});
            				console.log(error);
            			}
            		});
            	}else {
            		this.goEasy.im.topGroupConversation({
            			groupId: conversation.groupId,
            			top: !conversation.top,
            			onSuccess: function () {
            				uni.hideLoading();
            			},
            			onFailed: function (error) {
            				uni.hideLoading();
            				uni.showToast({
            					title: failedDescription,
            					icon: 'none'
            				});
            				console.log(error);
            			}
            		});
            	}
            },
            deleteConversation() {
            	uni.showLoading({
            		title:'加载中...',
            		mask: true
            	});
            	let failedDescription = '删除失败';
            	let conversation = this.actionPopup.conversation;
            	this.actionPopup.visible = false;
            
            	if(conversation.type === this.GoEasy.IM_SCENE.PRIVATE){
            		this.goEasy.im.removePrivateConversation({
            			userId: conversation.userId,
            			onSuccess: function () {
            				uni.hideLoading();
            			},
            			onFailed: function (error) {
            				uni.hideLoading();
            				uni.showToast({
            					title: failedDescription,
            					icon: 'none'
            				});
            				console.log(error);
            			}
            		});
            	}else {
            		this.goEasy.im.removeGroupConversation({
            			groupId: conversation.groupId,
            			onSuccess: function () {
            				uni.hideLoading()
            			},
            			onFailed: function (error) {
            				uni.hideLoading();
            				uni.showToast({
            					title: failedDescription,
            					icon: 'none'
            				});
            				console.log(error);
            			}
            		});
            	}
            },
            showAction (conversation) {
            	this.actionPopup.conversation = conversation;
            	this.actionPopup.visible = true;
            },
            renderConversations(content){
                console.log('打印这个',content)
                let data = content.conversations
                uni.setStorageSync('CallData',data)
                this.conversations = content.conversations
            	this.unreadTotal = content.unreadTotal;
            	this.setUnreadAmount(content.unreadTotal);
            },
            setUnreadAmount (unreadTotal) {
            	this.unreadTotal = unreadTotal;
            	if(this.unreadTotal > 0) {
            		
                    
            	}else{
            		uni.removeTabBarBadge({
            			index: 0
            		});
            	}
            },
            navigateToChat (conversation) {
                if(conversation.lastMessage.type!='addUser') {
                    let path = conversation.type === this.GoEasy.IM_SCENE.PRIVATE
                    		? '/pages/friend/privateChat/privateChat?id=' + conversation.userId
                    		: '/pages/friend/groupChat/groupChat?id=' + conversation.groupId+'&nickname='+conversation.data.name+'&avatar='+conversation.data.avatar;
                    uni.navigateTo({
                    	url: path
                    });
                } else {
                    return this.$jump('friend.request?type=' + 1);
                }
            	
            },
            connectGoEasy() {
                uni.showLoading()
                var user = uni.getStorageSync('userInfo');
                let that = this
                 if (user.id > 0) {
                     this.goEasy.connect({
                       id: user.id,
                       data: {
                         name: user.nickname,
                         avatar: user.avatar
                       },
                       onSuccess: () => {
                         console.log('GoEasy连接成功')
                       },
                       onFailed: (error) => {
                         console.log(' GoEasy连接失败, code:' + error.code + ',error:' + error.content);
                       },
                       onProgress: (attempts) => {
                         console.log('GoEasy is connecting重新连接次数', attempts);
                       }
                     });
                 }
            },
        },
        created() {
            uni.$on('toChat', message => {
                //console.log('index')
                this.$action.toChat(message);
            })
        },
        onShow() {
            console.log('打印这个----',this.goEasy.getConnectionStatus())
            if (this.goEasy.getConnectionStatus() === 'disconnected') {
                console.log('连接goeasy')
              this.connectGoEasy(); //连接goeasy
              // this.subscribeGroup(); //建立连接后，就应该订阅群聊消息，避免漏掉
            }
            //  this.listenConversationUpdate(); //监听会话列表变化
            //  this.loadConversations(); //加载会话列表
            this.initGoEasyListeners(); //监听来电
            this.unreadnum[0] = this.$action.setStatusTips()
            this.clickkey = false
            uni.setStorageSync('cache_key', '');
            uni.hideKeyboard();
            var userid = parseInt(uni.getStorageSync('access_token'));
            this.getuserinfo()
            this.check_update()
            
            if (userid > 0) {
                this.lastchat();
                
                this.$action.setStatusTips(); 
                
                if (uni.getStorageSync('ispush') == true) {

                    var message = uni.getStorageSync('pushmessage');
                    this.$action.toChat(message);
                    uni.setStorageSync('ispush', false)
                }
                

            } else {

                uni.setStorageSync('gourl', '/pages/index/index');

                this.$jump('login.index');
            }
        },
        onPullDownRefresh(e) {
            this.loadConversations(); //加载会话列表
        },
        onLoad() {
            
            var userid = parseInt(uni.getStorageSync('access_token'));
            if (userid > 0) {
                var that = this;
                
                this.$socket.on('chat', (res) => {
                    setTimeout(function() {
                        that.fresh_msg();
                    }, 100)
                })
                that.setrightmenu();
                setTimeout(function() {

                    api.getMyGroup({
                        userid: userid
                    }).then(res => {
                        console.log(res.data,'打印这是什么')
                        uni.setStorageSync(userid + '_groups', res.data)
                    })


                    api.getMyFriend({
                        userid: userid
                    }).then(resss => {
                        uni.setStorageSync(userid + '_frienddata', resss.data);
                    })
                }, 1000)

            }

        }
    }
</script>

<style lang="scss">
    page{ height: 100%; background: #fff; }
    .conversations{
    	width: 750rpx;
    	overflow-x: hidden;
    	display: flex;
    	flex-direction: column;
    	box-sizing: border-box;
    	height: 100%;
    }
    .conversations .scroll-item{
    	height: 152rpx;
    	display: flex;
    	align-items: center;
    	padding-left: 32rpx;
    }
    .conversations .scroll-item .head-icon{
    	width:100rpx;
    	height: 100rpx;
    	margin-right: 28rpx;
    }
    .conversations .scroll-item_info{
    	height: 151rpx;
    	width: 590rpx;
    	padding-right: 32rpx;
    	box-sizing: border-box;
    	border-bottom: 1px solid #EFEFEF;
    }
    .conversations .scroll-item_info .item-info-top{
    	padding-top: 20rpx;
    	height: 60rpx;
    	line-height: 60rpx;
    	display: flex;
    	align-items: center;
    	justify-content: space-between;
    
    }
    .conversations .item-info-top_name{
    	font-size: 34rpx;
    	color: #262628;
    }
    .conversations .item-info-top_time{
    	font-size: 26rpx;
    	color: rgba(179, 179, 179, 0.8);
    	font-family: Source Han Sans CN;
    }
    .conversations .item-info-bottom{
    	height: 40rpx;
    	line-height: 40rpx;
    	overflow: hidden;
    }
    .conversations .item-info-bottom-item{
    	display: flex;
    	justify-content: space-between;
    }
    .item-info-bottom .item-info-top_content{
    	font-size: 30rpx;
    	color: #b3b3b3;
    	overflow: hidden;
    	text-overflow:ellipsis;
    	white-space: nowrap;
    
    }
    
    .item-info-bottom .item-info-bottom_action{
    	width:50rpx;
    	height: 50rpx;
    	font-size: 20rpx;
    	background: url("../../static/images/action.png") no-repeat center;
    	background-size: 28rpx 30rpx;
    }
    .no-conversation{
    	width: 100%;
    	text-align: center;
    	height: 80rpx;
    	line-height: 80rpx;
    	font-size: 28rpx;
    	color: #9D9D9D;
    }
    .item-head{
    	position: relative;
    }
    .item-head .item-head_unread{
    	padding: 6rpx;
    	background-color: #EE593C;
    	color: #FFFFFF;
    	font-size: 24rpx;
    	line-height: 28rpx;
    	border-radius: 24rpx;
    	min-width: 24rpx;
    	min-height: 24rpx;
    	text-align: center;
    	position: absolute;
    	top:0;
    	right: 15rpx;
    }
    .action-container{
    	width: 100%;
    	height: 100%;
    	position: fixed;
    	top: 0;
    	left: 0;
    	display: flex;
    	justify-content: center;
    	align-items: center;
    }
    .action-container .layer{
    	position: absolute;
    	top: 0;
    	left: 0;
    	background: rgba(51, 51, 51, 0.5);
    	width: 100%;
    	height: 100%;
    	z-index: 99;
    }
    .action-box{
    	width: 400rpx;
    	height: 240rpx;
    	background: #ffffff;
    	position: relative;
    	z-index: 100;
    	border-radius: 20rpx;
    	overflow: hidden;
    }
    .action-item{
    	text-align: center;
    	line-height: 120rpx;
    	font-size: 34rpx;
    	color: #262628;
    	border-bottom: 1px solid #EFEFEF;
    }
    
    .unread-text {
    	color: #618DFF;
    }
    .fresh {
        height: 30px;
        line-height: 30px;
        font-size: 14px;
        text-align: center;
        color: #666;
    }

    .btn_yellow {
        background-color: yellow;
        color: #000;
        font-size: 12px;
        display: inline-block;
        height: 18px;
        line-height: 18px;
        padding: 0px 5px;
        border-radius: 5px;
        text-align: center;
        margin: 0px 2px;
    }

    .btn_green {
        background-color: #0aad6c;
        color: #fff;
        font-size: 12px;
        display: inline-block;
        height: 18px;
        line-height: 18px;
        padding: 0px 5px;
        border-radius: 5px;
        text-align: center;

        margin: 0px 2px;
    }

    .btn_blue {
        background-color: #2319dc;
        color: #fff;
        font-size: 12px;
        display: inline-block;
        height: 18px;
        line-height: 18px;
        padding: 0px 5px;
        border-radius: 5px;
        text-align: center;
        margin: 0px 2px;
    }

    .btn_grey {
        background-color: #ddd;
        color: #000;
        font-size: 12px;
        display: inline-block;
        height: 18px;
        line-height: 18px;
        padding: 0px 5px;
        border-radius: 5px;
        text-align: center;
        margin: 0px 2px;
    }

    .nodata {
        height: 35px;
        line-height: 35px;
        color: #666;
        font-size: 12px;
        text-align: center;
    }

    .item {
		background: #fff;
        height: 100upx;
        overflow: hidden;
        padding: 5px 30upx;
        display: flex;
        flex-direction: row;
        justify-content: flex-start;
        align-items: center;
        border-bottom:  1rpx solid #f4f4f4;
    }

    .istop {
        background-color: #e6e6e6;
    }

    .leftImg {
        width: 80upx;
        height: 80upx;
        margin-right: $uni-spacing-row-base;
        border-radius: $uni-border-radius-base;
        display: flex;
        flex-flow: wrap;
        justify-content: center;
        background-color: #eee;
        align-items: center;

        &:not(image) {
            padding: 1upx;
        }

        view,
        image {
            width: (76upx-2upx*4)/3;
            height: (76upx-2upx*4)/3;
            margin: 1upx;
        }
    }

    .rightContent {
        flex: 1;
        // border-bottom: 1px solid #fbfbfb;
    }

    .rightContent,
    .topCont {
        overflow: hidden;
        line-height: 50upx;
    }

    .topCont {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        vertical-align: top;
    }

    .userName {
        color: $uni-text-color;
        font-size: 15px;
    }

    .time {
        color: #999999;
        font-size: 20upx;
    }

    .bottomCont {
        width: 100%;
        font-size: 20upx;
        color: #999999;

        display: flex;
        align-items: center;
        justify-content: space-between;
        flex-direction: row;
    }

    .content {
        font-size: 20upx;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        word-break: break-all;
        height: 22px;
        line-height: 22px;
        display: flex;
        flex-direction: row;
        max-width: 100%;
    }

    .content text {
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        word-break: break-all;
        max-width: 100%;
    }

    .badge {
        background-color: red;
        color: #fff;
        border-radius: 40upx;
        line-height: 40upx;
        width: 40upx;
        height: 40upx;
        font-size: 24upx;
        text-align: center;
        flex-shrink: 0;
    }
</style>